import React, { Component } from 'react'
import {
  Text,
  Image,
  View,
  StyleSheet,
  Dimensions,
  Platform,
  PixelRatio,
  StatusBar,
  TouchableOpacity,
  WebView,
} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import ProgressBar from '../component/ProgressBar'
import {
  NavigationActions,
  px2dp,
  createAction,
  removeAsyncStorage,
} from '../utils'
import Base from './Base'

const { width, height } = Dimensions.get('window')
const isIOS = Platform.OS == 'ios'
const borderWidth = (isIOS ? 1.0 : 1.0) / PixelRatio.get()

class Browser extends Base {
  constructor(props) {
    super(props)
    this.state = {
      closeButtonEnabled: false,
      progress: 0,
      title: '加载中',
      uri: this.props.navigation.state.params.uri,
    }
    this.timelock = 0
  }
  static navigationOptions = ({ navigation }) => {
    const { params } = navigation.state
    return {
      title: '网页',
      headerTitleStyle: {
        alignSelf: 'center',
      },
      headerBackTitle: null,
      headerStyle: {
        backgroundColor: 'white',
        borderBottomWidth: 0,
        shadowColor: 'transparent',
        elevation: 1,
      },
      headerLeft: (
        <TouchableOpacity
          onPress={() => params.onBack && params.onBack()}
          style={{ width: 33, marginLeft: 10, justifyContent: 'center' }}
        >
          <Icon
            name="ios-arrow-back-outline"
            size={33}
            style={{ color: '#333' }}
          />
        </TouchableOpacity>
      ),
      headerRight: (
        <TouchableOpacity
          onPress={() => navigation.dispatch(NavigationActions.back())}
          style={{ width: 36, justifyContent: 'center' }}
        >
          <Icon name="ios-close" size={36} style={{ color: '#333' }} />
        </TouchableOpacity>
      ),
    }
  }
  goBack() {
    this.props.navigation.goBack()
  }
  onBack() {
    if (this.state.closeButtonEnabled) {
      this.refs.webview.goBack()
    } else {
      this.props.navigation.goBack()
    }
  }
  renderHeader() {
    return (
      <View style={{ height: isIOS ? 64 : 44, backgroundColor: 'white' }}>
        <View
          style={{
            marginTop: 20,
            flex: 1,
            paddingHorizontal: 10,
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <TouchableOpacity
            onPress={() => this.onBack()}
            style={{ width: 33, justifyContent: 'center' }}
          >
            <Icon
              name="ios-arrow-back-outline"
              size={33}
              style={{ color: '#333' }}
            />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => this.goBack()}
            style={{ width: 36, justifyContent: 'center' }}
          >
            <Icon name="ios-close" size={36} style={{ color: '#333' }} />
          </TouchableOpacity>
          <View
            style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}
          >
            <Text numberOfLines={1}>{this.state.title}</Text>
          </View>
          <View style={{ width: 36 }} />
          <View style={{ width: 33 }} />
        </View>
        {this.state.progress > 0 ? (
          <ProgressBar
            ref="progressBar"
            fillStyle={{}}
            backgroundStyle={{ backgroundColor: 'transparent' }}
            style={{ position: 'absolute', bottom: 0, width }}
            progress={this.state.progress}
          />
        ) : null}
      </View>
    )
  }
  onMessage(e) {
    const t = new Date().getTime()
    if (t - this.timelock < 500) {
      return
    }
    this.timelock = t
    const data = e.nativeEvent.data
    try {
      const s = data.split('#')
      if (s[0] == 'SKIP_TO_GOODS' && s[1]) {
        this.goto('Goods', { goodsId: s[1] })
      }
    } catch (err) {
      console.log(err)
    }
  }
  onShouldStartLoadWithRequest = e => {
    // 解决WebKitErrorDomain code:101的警告
    // http://leonhwa.com/blog/0014905236320002ebb3db97fe64fb3bb6f047eafb1c5de000

    const scheme = e.url.split('://')[0]

    if (scheme === 'http' || scheme === 'https') {
      return true
    }
    return false
  }
  onNavigationStateChange = navState => {
    let p = this.state.progress + 0.4 * Math.random()
    if (p >= 0.98) {
      p = 0.98
    }

    this.setState({
      closeButtonEnabled: navState.canGoBack,
      title: navState.title || '加载中',
      uri: navState.url,
      progress: p,
    })
  }
  onLoadStart = () => {
    this.setState({ progress: this.state.progress + 0.4 * Math.random() })
  }
  onLoadEnd = () => {
    this.startLoad = false
    this.setState({ progress: 1 })
    setTimeout(() => {
      this.setState({ progress: 0 })
    }, 150)
  }

  componentDidMount() {
    StatusBar.setBarStyle('default')
    this.props.navigation.setParams({ onBack: () => this.onBack() })
  }
  render() {
    const { uri } = this.state

    return (
      <View style={styles.container}>
        <WebView
          ref="webview"
          // automaticallyAdjustContentInsets={true}
          style={styles.webView}
          source={{ uri }}
          javaScriptEnabled
          domStorageEnabled
          decelerationRate="normal"
          injectedJavaScript="function youqiSkip(id){window.postMessage('SKIP_TO_GOODS#'+id)}"
          onMessage={e => this.onMessage(e)}
          onLoadStart={this.onLoadStart}
          onLoadEnd={this.onLoadEnd}
          onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest}
          onNavigationStateChange={this.onNavigationStateChange}
          startInLoadingState
          scalesPageToFit={false}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#e5e5e5',
  },
  webView: {
    flex: 1,
    backgroundColor: '#e5e5e5',
  },
})

export default Browser
